// 登录与注册的模块
import { reqGetCode, reqUseregister, reqUserLogin, reqGetUserInfo, reqUserLogout } from "@/api"

// state: 数据对象
const state = {
    // 验证码
    code: '',
    // 服务器下发的用户唯一标识
    token: localStorage.getItem('TOKEN'),
    userinfo: {}
}

// mutations：专门用于修改state中的数据
const mutations = {
    // 修改state中的code属性
    GETCODE(state, code) {
        state.code = code
    },
    // 修改state中的token属性
    USERLOGIN(state, token) {
        state.token = token
    },
    // 修改state中的用户信息
    GETUSERINFO(state, userinfo) {
        state.userinfo = userinfo
    },
    // 清除仓库数据和本地数据
    CLEAR(state) {
        state.token = ''
        state.userinfo = {}
        localStorage.removeItem('TOKEN')
    }
}

// action：书写业务逻辑，进行异步处理
const actions = {
    // 发送请求获取验证码
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone)
        if (result.code == 200) {
            commit("GETCODE", result.data);
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },

    // 发送请求注册用户
    async userRegister({ commit }, user) {
        let result = await reqUseregister(user);
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },

    // 发送请求登录用户
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data);
        // 重中之重 token:服务器下发给用户的唯一标识，后续需要通过token想服务器获取用户信息
        if (result.code == 200) {
            commit("USERLOGIN", result.data.token);
            // 持久化存储token
            localStorage.setItem("TOKEN", result.data.token);
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },

    // 获取用户信息：请求头必须携带token才能获取
    async getUserInfo({ commit }) {
        let result = await reqGetUserInfo();
        if (result.code == 200) {
            commit("GETUSERINFO", result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 退出登录
    async userLogout({ commit }) {
        let result = await reqUserLogout();
        console.log(result)
        if (result.code == 200) {
            commit("CLEAR")
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    }

}

// getters：类似计算属性
const getters = {}

export default {
    state,
    mutations,
    actions,
    getters
}